package com.kedacom.general.util;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


public class FileUtils {

    public static Map<String,String> multipartFileToBase64 (HttpServletRequest request) {
        try{
            MultipartHttpServletRequest mureq = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> files = mureq.getFileMap();
            if(files.isEmpty()){
                return null;
            }
            MultipartFile file = files.get(files.keySet().iterator().next());

            byte[] fileByte = null;
            try {
                    fileByte = file.getBytes();
            } catch (IOException e) {
                    return null;
            }
            String voiceBase64= Base64.getEncoder().encodeToString(fileByte);
            String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
            voiceBase64=voiceBase64 + "," + type;
            HashMap<String, String> resultMap = new HashMap<>();
            resultMap.put(files.keySet().iterator().next(),voiceBase64);
            return resultMap;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
